//
//  RegViewController.m
//  CurvesFit
//
//  Created by liu on 2016/11/24.
//  Copyright © 2016年 Nci Technology Inc. All rights reserved.
//

#import "RegViewController.h"
#import "UIView+Extension.h"
#import "PickerChoiceView.h"
#import "AppDelegate.h"
#import <AudioToolbox/AudioToolbox.h>
#define kWidth self.view.frame.size.width
#define SHeight  [UIScreen mainScreen].bounds.size.height
@interface RegViewController ()<UITextFieldDelegate,TFPickerDelegate>
{
    NSInteger selectIndex;
    UITextField *_genTextField;
    UITextField *_wetTextField;
    UITextField *_hetTextField;
    UITextField *_actTextField;
    UITextField *_birthTextField;
    UIButton *_btn;
    UIActivityIndicatorView* _actView;
}

@property (nonatomic,strong)NSMutableArray *mutArray;

@end

@implementation RegViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBackgroundImageWithImageName:@"ic-launch3"];
    self.navigationItem.rightBarButtonItem = nil;
    
    [self uiResConfig];
}

-(void)uiResConfig {

    UILabel *tipLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 75, kWidth - 20, 20)];
    tipLable.textAlignment = NSTextAlignmentCenter;
    tipLable.textColor = [UIColor whiteColor];
    tipLable.font = Bold(16);
    tipLable.text = [NSLocalizedString(@"Personal Information", nil) uppercaseString];
    [self.view addSubview:tipLable];
    
    NSArray *array = @[NSLocalizedString(@"Gender", nil) ,NSLocalizedString(@"Weight", nil),NSLocalizedString(@"Height", nil),NSLocalizedString(@"Active Level", nil) ,NSLocalizedString(@"Date of Birth", nil)];
    
    for (int i = 0; i<array.count; i++) {
        
        UIView *mView = [[UIView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(tipLable.frame) + 30 + (SHeight / 16.7 + 30) * i, kWidth - 30, (SHeight / 16.7 + 30))];
        mView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:mView];
        
        UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, mView.frame.size.width, 20)];
        lable.textColor = [UIColor whiteColor];
        lable.font = Regular(16);
        lable.text = array[i];
        [mView addSubview: lable];
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(lable.frame) + 5, mView.frame.size.width, SHeight / 16.7)];
        textField.textColor = [UIColor whiteColor];
        textField.backgroundColor = [UIColor clearColor];
        textField.font = [UIFont systemFontOfSize: 16];
        textField.borderStyle = UITextBorderStyleRoundedRect;
        textField.tag = 1000 + i;
        textField.layer.cornerRadius = 6.0f;
        textField.layer.borderWidth = 1.0f;
        textField.layer.borderColor = [UIColor whiteColor].CGColor;
        textField.delegate = self;
        
        textField.keyboardType = UIKeyboardTypeEmailAddress;
        textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        textField.placeholder = @"";
        [mView addSubview: textField];
        
    }
    
    _btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btn.frame = CGRectMake(15, SHeight - (SHeight / 16.7) - 20, kWidth - 30, SHeight / 16.7);
    
    [_btn addTarget:self action:@selector(commitButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    _btn.backgroundColor = [UIColor colorWithRed:0.84 green:0.13 blue:0.46 alpha:1.00];
    _btn.layer.cornerRadius = 8;
    _btn.tintColor = [UIColor whiteColor];
    [_btn setTitle:NSLocalizedString(@"CONTINUE", nil)/*@"SIGN UP"*/ forState:UIControlStateNormal];
    _btn.titleLabel.font = Regular(16);
    [self.view addSubview:_btn];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    NSLog(@"%ld",textField.tag);
    selectIndex = textField.tag;
    PickerChoiceView *picker = [[PickerChoiceView alloc]initWithFrame:self.view.bounds];
    picker.delegate = self;
    if (textField.tag == 1000) {
        _genTextField = textField;
        picker.arrayType = GenderArray;
        
    }if (textField.tag == 1001) {
        _wetTextField = textField;
        picker.arrayType = WeightArray;
        
    }if (textField.tag == 1002) {
       _hetTextField = textField;
        picker.arrayType = HeightArray;
        
    }if (textField.tag == 1003) {
       _actTextField = textField;
        picker.arrayType = ActiveArray;
        
    }if (textField.tag == 1004) {
        _birthTextField = textField;
        picker.arrayType = DeteArray;
    }
    
    [self.view addSubview:picker];
    
    return NO;
}

#pragma mark -------- TFPickerDelegate
- (void)PickerSelectorIndixString:(NSString *)str{
    
    NSInteger index = selectIndex - 1000;
    
    NSDictionary *dict = [self.mutArray objectAtIndex:index];
    
    NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    [muDict setObject:str forKey:@"title2"];
    [self.mutArray replaceObjectAtIndex:index withObject:muDict];
    
    UITextField *textField = (UITextField *)[self.view viewWithTag:selectIndex];
    textField.text = str;
    if (selectIndex == 1001) {
        textField.text = [NSString stringWithFormat:@"%@kg",textField.text];
    } else if (selectIndex == 1002) {
        textField.text = [NSString stringWithFormat:@"%@cm",textField.text];
    }
}

-(void)commitButtonClicked:(UIButton *)sender {
    
    if ([_genTextField.text length] == 0 || [_wetTextField.text length] == 0 || [_hetTextField.text length] == 0 || [_actTextField.text length] == 0 || [_birthTextField.text length] == 0) {
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"选项都为必填项" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alter show];
        return;
    }
    
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    LoginBodyInfo * bodyInfo = pApp.m_bodyInfo;
    NSInteger nBodyId = bodyInfo.m_nBodyId;
    /*if(nBodyId < 1) {
     _lblPersonInfoTips.text = @"Body ID? Please Login.";
     AudioServicesPlaySystemSound(1109);
     return;
     }*/
    
    
    
    if(_actView == nil) {
        CGRect rt = _btn.frame;
        rt.origin.x += rt.size.width - rt.size.height * 2;
        rt.size.width = rt.size.height;
        _actView = [[UIActivityIndicatorView alloc] initWithFrame:rt];
        _actView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        _actView.hidesWhenStopped = YES;
        [self.view addSubview:_actView];
    }
    _btn.hidden = YES;
    [_actView startAnimating];
    
    //create User info JSON data
    /*int nLocId = _sSelectedLocId.intValue;
     if(nLocId <= 0) {
     [_actView stopAnimating];
     _btnProfSubmit.hidden = NO;
     _lblPersonInfoTips.text = @"Please Select Club Location!";
     AudioServicesPlaySystemSound(1112);
     return;
     }*/
    //_lblPersonInfoTips.text = [NSString stringWithFormat:@"%d", nLocId];
    //return;
    
    short nGender = 0;
    
    if ([_genTextField.text isEqualToString:@"male"]) {
        nGender = 1;
    }
    
    Byte nActLvl = 0;
    
    if ([_actTextField.text isEqualToString:NSLocalizedString(@"Ordinary", nil)]) {
        nGender = 0;
    } else if ([_actTextField.text isEqualToString:NSLocalizedString(@"Amateur", nil)]) {
        nGender = 1;
    } else if ([_actTextField.text isEqualToString:NSLocalizedString(@"Professional", nil)]) {
        nGender = 2;
    }
    
//    NSInteger nUnit = _scWgtUnit.selectedSegmentIndex;
//    NSString* sUnit = [NSString stringWithFormat:@"%ld", (long)(nUnit+1)];
//    NSString* sWgt = _txtBodyWgt.text;
//    float fHgt = 0.0;
//    if (nUnit == 1)
//        fHgt = _txtBodyHgt.text.intValue + (_txtHgtInch.text.intValue / 12.0);
//    else
//        fHgt = _txtBodyHgt.text.intValue / 100.0;
//    short nActLvl = _scActLevel.selectedSegmentIndex;
    
    NSDictionary *regInfo = @{
                              @"BodyId" : [NSString stringWithFormat:@"%ld", (long)nBodyId],
                              @"LocationId" : @"0",
                              @"Gender" : [NSString stringWithFormat:@"%d", nGender],
                              @"BodyHgt" : _hetTextField.text,
                              @"BodyWgt" : _wetTextField.text,
                              @"WgtUnit" : @"kg",
                              @"HgtUnit" : @"cm",
                              @"BodyBirthDay" :  _birthTextField.text,
                              @"FitLvl" : [NSString stringWithFormat:@"%d",nActLvl],
                              @"ChestSize" : @"0",
                              @"WaistLine" :  @"0"
                              };
    NSMutableURLRequest *request = [pApp requestWebApiRouter:@"POST" url:@"Mob" data:regInfo];
    
    
    // 6.发送请求
    //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data == nil || connectionError)
            return;
        
        [_actView stopAnimating];
        _btn.hidden = NO;
        NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        sRecv = [sRecv substringFromIndex:1];
        if([sRecv hasPrefix:@"Failed"]) {
//            _lblPersonInfoTips.text = sRecv;
            AudioServicesPlaySystemSound(1109);
            return;
        }
        NSString* sTagId = [sRecv substringWithRange: NSMakeRange(0, sRecv.length-1)];
        
        NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
        [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
        [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
        NSDate* dtBorn = [inputFormatter dateFromString:_birthTextField.text];
        
        [pApp storeRegBodyInfo:nBodyId tag:sTagId gerder:(Byte)nGender born:dtBorn wgt:_wetTextField.text.floatValue wun:0
                           hgt:_hetTextField.text.floatValue hun:0 lvl:(Byte)nActLvl email:nil first:nil last:nil store:@"0"];
        [pApp enterMainPage];
    }];
}
@end
